﻿using GYCTOAManagementSystemNewApi.Model.Tool;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GYCTOAManagementSystemNewApi.Public
{
    /// <summary>
    /// 全局方法过滤器
    /// </summary>
    public class CustomerActionFilterAttribute: ActionFilterAttribute, IActionFilter
    {
        /// <summary>
        /// 不参与权限判断与过滤
        /// </summary>
        public bool IsCheck = true;

        /// <summary>
        /// 方法操作权限判断
        /// </summary>
        public string OperateRight { get; set; }
        public override void OnActionExecuted(ActionExecutedContext context)
        {
           
        }

        public override void OnActionExecuting(ActionExecutingContext context )
        { 
            #region 验证是否有方法的操作权限
            bool result = false;
            if (!string.IsNullOrEmpty(OperateRight))
            {
                //var right = Public.GetRight().UserData;
                var author = context.HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
                var right = TokenManage.GetTokenValues(author)[2].Value;
                if (right.Contains("Admin"))
                    return;
                var rights = right.Split(',');
                foreach (var r in rights)
                {
                    if (!string.IsNullOrWhiteSpace(r) && OperateRight.Contains(r))
                        result = true;
                }
                if (!result)
                {
                    context.Result = new JsonResult(new
                    {
                        msg = new Message
                        {
                            IsSuccess = false,
                            Msg = "您不具有当前操作的权限，请联系系统管理员",
                        }
                    });
                    return;
                }

            }
            #endregion
        }
    }
}
